/**
 * 
 */
package com.yangtao.prototype.system.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yangtao.framework.service.BaseService;
import com.yangtao.framework.util.StringHelper;
import com.yangtao.prototype.system.dao.RoleDAO;
import com.yangtao.prototype.system.dao.UserDAO;
import com.yangtao.prototype.system.entity.SysUser;
import com.yangtao.prototype.system.entity.UserRole;
import com.yangtao.prototype.system.user.service.UserModel;
import com.yangtao.prototype.system.user.service.UserService;

/**
 * @author 杨涛
 * 
 */
@Service
public class UserServiceImpl extends BaseService implements UserService {

	@Autowired
	private UserDAO userDAO;
	// @Autowired
	// private OrganizeDAO sd;
	@Autowired
	private RoleDAO rd;

	@Override
	public UserModel delete(UserModel model) {
		userDAO.delete(model.getDomain());
		model.addInfo("删除成功!");
		return model;
	}

	@Override
	public UserModel list(UserModel model) {
		userDAO.findPageByExample(model.getPage(), model.getDomain());
		return model;
	}

	@Override
	public UserModel load(UserModel model) {
		if (StringHelper.isNotEmpty(model.getDomain().getId())) {
			model.setDomain(userDAO.load(model.getDomain().getId()));
		}
		return model;
	}

	@Override
	public UserModel save(UserModel model) {
		SysUser user = model.getDomain();
		// 删除用户原有的角色
		userDAO.deleteUserRoles(user.getId());
		if (StringHelper.isNotEmpty(model.getUserRoles())) {
			String[] roles = model.getUserRoles().split(",");
			List<UserRole> urs = new ArrayList<UserRole>();
			for (String role : roles) {
				UserRole ur = new UserRole();
				ur.setRole(rd.load(role));
				ur.setUser(user);
				urs.add(ur);
			}
			user.setRoles(urs);
		}
		userDAO.saveOrUpdate(user);
		model.addInfo("save.success");
		return model;
	}

	@Override
	public UserModel loadPracticableResource(UserModel model) {
		String userId = model.getDomain().getId();
		model.setDistributeRoles(userDAO.findDistributeRoles(userId));
		model.setUnDistributeRoles(userDAO.findUnDistributeRoles(userId));
		return model;
	}

	@Override
	public UserModel loadSelect(UserModel model) {
		// TODO Auto-generated method stub
		return null;
	}
}
